import React, { useMemo, useState } from "react";
import { useModel } from "@umijs/max";
import { Button, DatePicker, Form, Input, Space, Table } from "antd";
import XlSelect from "@/components/Form/XlSelect";
import { PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from 'antd/es/table';
import { cabinetTypes } from "@/constants/types";
import XlCheckBox from "@/components/Form/XlCheckBox";
import { cabinetNodeMaps  } from "@/constants/dictData";
import { calculateTableWidth } from "@/utils/util";
import { fetchBookingList, fetchBookingTabNum } from '../services';
import { useComponentDidMount } from "@/hooks";
import { useRequest } from "ahooks";
import { fetchServiceProviderOptions } from "@/pages/BasicInfo/services";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import BookingModal from "../modals/BookingModal";
import { bookingAdd, bookingUpdate, bookingTag } from "../services";
import TrackMarking from "../modals/TrackMarking";
import { history } from "@umijs/max";

const {Item} = Form;

const CabinetTrack = () => {
  const [form] = Form.useForm();
  const {data: servicesList} = useRequest(async () => {
    const res = await fetchServiceProviderOptions({type: 'peerSupplier'});
    return (res || []).map((v: any) => ({label: v.name,value: v.code}));
  })

  const {getDict} = useModel('dictModel');
  const cabinetTypes = getDict('cabinetType');
  //
  const {loading: addLoading, runAsync: bookingAddApi} = useRequest(bookingAdd, {manual: true});
  const {loading: updateLoading, runAsync: bookingUpdateApi} = useRequest(bookingUpdate, {manual: true});
  // 
  const {loading: bookingTagLoading, runAsync: bookingTagApi} = useRequest(bookingTag, {manual: true});

  // 
  const [visible, setVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<cabinetTypes | null>(null);
  //
  const [tagVisible, setTagVisible] = useState(false);
  // order status 
  const [node, setNode] = useState<string []>(['all']);
  const [tabNumObj, setTabNumObj] = useState<any>({});

  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    total: 0,
    pageNum: 1,
    pageSize: 20
  });


  const fetchTabNumApi = (params: any = {}) => {
    fetchBookingTabNum(params).then(
      res => {
        setTabNumObj(res || {});
      }
    )
  }

  // 查询
  const search = async (params: any) => {
    const res = await fetchBookingList({
      ...params,
      nodes: !params?.nodes || !params?.nodes?.length || params?.nodes?.includes('all') ? undefined : params?.nodes
    });
    setDataSource(res?.data || []);
    setPagination({
      total: res?.total,
      pageNum: res?.pageNum,
      pageSize: res?.pageSize
    });
  }

  const getParams = () => {
    const params = form.getFieldsValue();
    return {
      ...params,
      cabinetTimeBegin: params?.cabinetTime?.[0] ? params?.cabinetTime?.[0].format('YYYY-MM-DD 00:00:00') : undefined,
      cabinetTimeEnd: params?.cabinetTime?.[1] ? params?.cabinetTime?.[1].format('YYYY-MM-DD 23:59:59') : undefined,
      cabinetTime: undefined
    }
  }

  const handleSearch = () => {
    const params = getParams();
    search({
      ...params,
      nodes: node,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }
  const handleReset = () => {
    form.resetFields();
    search({
      nodes: node,
      pageNum: 1,
      pageSize: 20
    });
  }
  

  // 开柜
  const bookingProps = {
    visible,
    currentRow,
    loading: addLoading || updateLoading,
    title: currentRow ? '编辑柜子' : '新增柜子',
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: cabinetTypes) => {
      const requestFunc = currentRow ? bookingUpdateApi : bookingAddApi;
      const res = await requestFunc({...params, id: currentRow ? currentRow?.id : undefined});
      if (res?.code === '0') {
        bookingProps.onCancel();
        handleSearch();
      }
    }
  }
  // 打标
  const trackMarkingProps = {
    visible: tagVisible,
    loading: bookingTagLoading,
    currentRow,
    title: '柜子轨迹打标',
    onCancel: () => {
      setTagVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      const res = await bookingTagApi(params);
      if (res?.code === '0') {
        trackMarkingProps.onCancel();
        handleSearch();
      }
    }
  }



  // 创建订单
  const handleBooking = () => {
    setVisible(true);
  }
  // node change
  const handleNodeChange = (val: string []) => {
    const params = getParams();
    setNode(val);
    search({
      ...params,
      nodes: val,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }
  // 编辑柜子
  const handleCabinetEdit = (record: cabinetTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  // 柜子详情
  const handleCabinetView = (record: cabinetTypes) => {
    history.push(`/order-manage/cabinet-detail?id=${record?.id}`);
  }
  // 打标
  const handleCabinetTag = (record: cabinetTypes) => {
    setCurrentRow(record);
    setTagVisible(true);
  }

  const columns: ColumnsType<cabinetTypes> = [
    {
      title: '装柜类型',
      dataIndex: 'type',
      width: 120,
      render: (_, record: cabinetTypes) => <XlTableDictColumn value={record?.type} type="cabinetType" />
    },
    {
      title: '同行名称',
      dataIndex: 'peerSupplierName',
      ellipsis: true,
      width: 150
    },
    {
      title: '操作单号',
      dataIndex: 'bookingCode',
      width: 150
    },
    {
      title: '柜号',
      dataIndex: 'cabinetCode',
      width: 150
    },
    {
      title: 'SO',
      dataIndex: 'so',
      width: 150
    },
    {
      title: '轨迹状态',
      dataIndex: 'bookingStatusText',
      width: 120
    },
    {
      title: '船司',
      dataIndex: 'shipName',
      ellipsis: true,
      width: 150
    },
    {
      title: '航名航次',
      dataIndex: 'shipLineNo',
      width: 150
    },
    {
      title: '线路名称',
      dataIndex: 'lineName',
      width: 180
    },
    {
      title: '业务时间',
      dataIndex: 'businessTime',
      width: 180
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: 200
    },
    {
      title: '操作',
      dataIndex: 'options',
      width: 280,
      fixed: 'right',
      render: (_, record) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleCabinetEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleCabinetView(record)}>查看</Button>
            {record?.bookingStatus !== '0720' && <Button type="link" onClick={() => handleCabinetTag(record)}>轨迹打标</Button>}
          </Space>
        );
      }
    },
  ];

  const composeCabinetNodeMaps = useMemo(() => {
    return cabinetNodeMaps.map((v: any) => ({
      ...v,
      label: tabNumObj?.[v?.num] > 0 ? `${v?.label} (${tabNumObj?.[v?.num]})` : v.label
    }))
  }, [JSON.stringify(tabNumObj), JSON.stringify(cabinetNodeMaps)]);

  useComponentDidMount(() => {
    search({
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
  })

  return (
    <>
      <Form form={form} layout="inline">
        <Item label="装柜时间" name="cabinetTime" style={{marginBottom: 15}}>
          <DatePicker.RangePicker />
        </Item>
        <Item label="业务类型" name="type" style={{marginBottom: 15}}>
          <XlSelect options={cabinetTypes} style={{width: 183}} />
        </Item>
        <Item label="供应商" name="peerSupplierId" style={{marginBottom: 15}}>
          <XlSelect options={servicesList} style={{width: 183}} />
        </Item>
        <Item label="柜号虚拟柜号" name="cabinetCode" style={{marginBottom: 15}}>
          <Input style={{width: 183}} />
        </Item>
        <Item label="SO" name="so" style={{marginBottom: 15}}>
          <Input style={{width: 183}} />
        </Item>
        <Space>
          <Button type="primary" onClick={handleSearch}>查询</Button>
          <Button type="default" onClick={handleReset}>重置</Button>
        </Space>
      </Form>
      <div style={{display: 'flex', justifyContent:'space-between', flexWrap: 'wrap'}}>
        <div style={{marginTop: 20}}>
          <XlCheckBox.ButtonGroup totalNum={tabNumObj?.totalNum} hasAll value={node} onChange={(val: string []) => handleNodeChange(val)} options={composeCabinetNodeMaps} />
        </div>
        <Space style={{display: 'flex', justifyContent: 'flex-end', marginTop: 20}}>
          <Button type="primary" onClick={handleBooking}><PlusOutlined />新建柜子</Button>
          <Button type="primary"><PlusOutlined />批量导入轨迹</Button>
        </Space>
      </div>
      <Table
        className="mt10"
        rowKey="id"
        bordered
        dataSource={dataSource}
        columns={columns}
        scroll={{x: calculateTableWidth(columns), y: 600}}
        pagination={{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            const params = getParams();
            search({
              ...params,
              pageNum,
              pageSize
            });
          }
        }}
      />
      {visible && <BookingModal {...bookingProps} />}
      {tagVisible && <TrackMarking {...trackMarkingProps} />}
    </>
  );
}
export default CabinetTrack;